<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { useUniAppSystemRectInfo } from '@tuniao/tnui-vue3-uniapp/hooks'
import TnNavbar from '@tuniao/tnui-vue3-uniapp/components/navbar/src/navbar.vue'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnIcon from '@tuniao/tnui-vue3-uniapp/components/icon/src/icon.vue'
import TnModal from '@tuniao/tnui-vue3-uniapp/components/modal/src/modal.vue'
import TnLoading from '@tuniao/tnui-vue3-uniapp/components/loading/src/loading.vue'
import TnToast from '@tuniao/tnui-vue3-uniapp/components/toast/src/toast.vue'

import { useAppI18n } from '@/hooks/use-i18n'

const { navBarInfo } = useUniAppSystemRectInfo()
const { t } = useAppI18n()

// 用户VIP信息
const userVipInfo = reactive({
  isVip: false,
  vipLevel: 0,
  vipExpireTime: '',
  remainingTimes: 5,
  totalTimes: 10
})

// VIP套餐数据
const vipPackages = ref([
  {
    id: 1,
    name: '月度VIP',
    price: 19.9,
    originalPrice: 39.9,
    duration: '30天',
    features: ['无限使用次数', '优先客服支持', '专属主题', '无广告体验'],
    popular: false,
    discount: '5折'
  },
  {
    id: 2,
    name: '年度VIP',
    price: 99.9,
    originalPrice: 199.9,
    duration: '365天',
    features: ['无限使用次数', '优先客服支持', '专属主题', '无广告体验', '专属功能'],
    popular: true,
    discount: '5折'
  },
  {
    id: 3,
    name: '永久VIP',
    price: 299.9,
    originalPrice: 599.9,
    duration: '永久',
    features: ['无限使用次数', '优先客服支持', '专属主题', '无广告体验', '专属功能', '终身更新'],
    popular: false,
    discount: '5折'
  }
])

// 广告奖励数据
const adRewards = ref([
  {
    id: 1,
    name: '观看视频广告',
    reward: '+3次使用',
    duration: '30秒',
    icon: 'video-fill',
    color: 'tn-gradient-bg__cool-1'
  },
  {
    id: 2,
    name: '分享给好友',
    reward: '+5次使用',
    duration: '立即获得',
    icon: 'share-fill',
    color: 'tn-gradient-bg__cool-2'
  },
  {
    id: 3,
    name: '邀请好友注册',
    reward: '+10次使用',
    duration: '好友注册后',
    icon: 'user-add-fill',
    color: 'tn-gradient-bg__cool-3'
  }
])

// 状态管理
const showPurchaseModal = ref(false)
const showAdModal = ref(false)
const showSuccessModal = ref(false)
const isLoading = ref(false)
const selectedPackage = ref(null)
const selectedAd = ref(null)

// 计算属性
const progressPercentage = computed(() => {
  return (userVipInfo.remainingTimes / userVipInfo.totalTimes) * 100
})

const isVipExpired = computed(() => {
  if (!userVipInfo.isVip) return true
  if (!userVipInfo.vipExpireTime) return true
  return new Date(userVipInfo.vipExpireTime) < new Date()
})

// 购买VIP
const purchaseVip = (pkg: any) => {
  selectedPackage.value = pkg
  showPurchaseModal.value = true
}

// 确认购买
const confirmPurchase = async () => {
  if (!selectedPackage.value) return
  
  isLoading.value = true
  
  try {
    // 模拟支付过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 更新用户VIP信息
    userVipInfo.isVip = true
    userVipInfo.vipLevel = selectedPackage.value.id
    userVipInfo.remainingTimes = 999 // 无限次数
    userVipInfo.totalTimes = 999
    
    // 设置过期时间
    const now = new Date()
    if (selectedPackage.value.duration === '30天') {
      userVipInfo.vipExpireTime = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString()
    } else if (selectedPackage.value.duration === '365天') {
      userVipInfo.vipExpireTime = new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000).toISOString()
    } else {
      userVipInfo.vipExpireTime = '永久'
    }
    
    showPurchaseModal.value = false
    showSuccessModal.value = true
    
    // 显示成功提示
    uni.showToast({
      title: '购买成功！',
      icon: 'success'
    })
    
  } catch (error) {
    uni.showToast({
      title: '购买失败，请重试',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 观看广告
const watchAd = (ad: any) => {
  selectedAd.value = ad
  showAdModal.value = true
}

// 确认观看广告
const confirmWatchAd = async () => {
  if (!selectedAd.value) return
  
  isLoading.value = true
  
  try {
    // 模拟广告播放
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    // 增加使用次数
    const reward = parseInt(selectedAd.value.reward.match(/\d+/)[0])
    userVipInfo.remainingTimes += reward
    userVipInfo.totalTimes += reward
    
    showAdModal.value = false
    
    // 显示成功提示
    uni.showToast({
      title: `获得${selectedAd.value.reward}`,
      icon: 'success'
    })
    
  } catch (error) {
    uni.showToast({
      title: '观看失败，请重试',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 使用功能
const useFeature = () => {
  if (userVipInfo.isVip && !isVipExpired.value) {
    uni.showToast({
      title: 'VIP用户可无限使用',
      icon: 'success'
    })
    return
  }
  
  if (userVipInfo.remainingTimes > 0) {
    userVipInfo.remainingTimes--
    uni.showToast({
      title: '使用成功',
      icon: 'success'
    })
  } else {
    uni.showToast({
      title: '使用次数不足，请观看广告或购买VIP',
      icon: 'none'
    })
  }
}
</script>

<template>
  <view class="vip-page">
    <!-- 自定义导航栏 -->
    <TnNavbar
      :fixed="true"
      :transparent="false"
      title="VIP会员"
      :background-color="'#ffffff'"
      :color="'#000000'"
    />
    
    <view class="page-content">
      <!-- VIP状态卡片 -->
      <view class="vip-status-card tn-white_bg">
        <view class="status-header">
          <view class="vip-icon" :class="userVipInfo.isVip ? 'vip-active' : 'vip-inactive'">
            <TnIcon name="vip" :color="userVipInfo.isVip ? '#FFD700' : '#999'" />
          </view>
          <view class="status-info">
            <view class="status-title">
              {{ userVipInfo.isVip ? 'VIP会员' : '普通用户' }}
            </view>
            <view class="status-desc">
              {{ userVipInfo.isVip ? 
                (isVipExpired ? '会员已过期' : `有效期至：${userVipInfo.vipExpireTime}`) : 
                '升级VIP享受更多特权' 
              }}
            </view>
          </view>
        </view>
        
        <!-- 使用次数进度 -->
        <view class="usage-progress">
          <view class="progress-header">
            <text>使用次数</text>
            <text>{{ userVipInfo.remainingTimes }}/{{ userVipInfo.totalTimes }}</text>
          </view>
          <view class="progress-bar">
            <view 
              class="progress-fill" 
              :style="{ width: `${progressPercentage}%` }"
            ></view>
          </view>
        </view>
        
        <!-- 测试按钮 -->
        <TnButton 
          type="primary" 
          size="lg" 
          @click="useFeature"
          :disabled="userVipInfo.remainingTimes === 0 && !userVipInfo.isVip"
        >
          {{ userVipInfo.isVip ? '使用功能（VIP无限）' : '使用功能' }}
        </TnButton>
      </view>

      <!-- VIP套餐 -->
      <view class="vip-packages">
        <view class="section-title">VIP套餐</view>
        <view class="package-list">
          <view 
            v-for="pkg in vipPackages" 
            :key="pkg.id"
            class="package-item tn-white_bg"
            :class="{ 'popular': pkg.popular }"
          >
            <view v-if="pkg.popular" class="popular-badge">推荐</view>
            <view class="package-header">
              <view class="package-name">{{ pkg.name }}</view>
              <view class="package-price">
                <text class="current-price">¥{{ pkg.price }}</text>
                <text class="original-price">¥{{ pkg.originalPrice }}</text>
                <view class="discount-badge">{{ pkg.discount }}</view>
              </view>
            </view>
            <view class="package-duration">{{ pkg.duration }}</view>
            <view class="package-features">
              <view 
                v-for="feature in pkg.features" 
                :key="feature"
                class="feature-item"
              >
                <TnIcon name="check-fill" color="#52c41a" size="24rpx" />
                <text>{{ feature }}</text>
              </view>
            </view>
            <TnButton 
              type="primary" 
              size="sm" 
              @click="purchaseVip(pkg)"
              :custom-style="{ marginTop: '20rpx' }"
            >
              立即购买
            </TnButton>
          </view>
        </view>
      </view>

      <!-- 广告奖励 -->
      <view class="ad-rewards">
        <view class="section-title">免费获取使用次数</view>
        <view class="reward-list">
          <view 
            v-for="ad in adRewards" 
            :key="ad.id"
            class="reward-item tn-white_bg"
            @click="watchAd(ad)"
          >
            <view class="reward-icon" :class="ad.color">
              <TnIcon :name="ad.icon" color="#fff" />
            </view>
            <view class="reward-info">
              <view class="reward-name">{{ ad.name }}</view>
              <view class="reward-desc">{{ ad.duration }}</view>
            </view>
            <view class="reward-value">{{ ad.reward }}</view>
            <TnIcon name="right" color="#999" />
          </view>
        </view>
      </view>
    </view>
  </view>

  <!-- 购买确认弹窗 -->
  <TnModal
    v-model="showPurchaseModal"
    title="确认购买"
    :content="`确定要购买 ${selectedPackage?.name} 吗？`"
    confirm-text="确认购买"
    cancel-text="取消"
    @confirm="confirmPurchase"
  />

  <!-- 广告观看弹窗 -->
  <TnModal
    v-model="showAdModal"
    title="观看广告"
    :content="`观看 ${selectedAd?.duration} 广告获得 ${selectedAd?.reward}`"
    confirm-text="开始观看"
    cancel-text="取消"
    @confirm="confirmWatchAd"
  />

  <!-- 购买成功弹窗 -->
  <TnModal
    v-model="showSuccessModal"
    title="购买成功"
    content="恭喜您成为VIP会员！现在可以享受无限使用次数和专属特权。"
    confirm-text="知道了"
    :show-cancel="false"
  />

  <!-- 加载中 -->
  <TnLoading v-model="isLoading" text="处理中..." />
</template>

<style lang="scss" scoped>
.vip-page {
  min-height: 100vh;
  background-color: var(--tn-color-gray-light);
}

.page-content {
  padding: 30rpx;
  padding-top: calc(30rpx + 88px);
}

// VIP状态卡片
.vip-status-card {
  border-radius: 30rpx;
  padding: 40rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

  .status-header {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;

    .vip-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
      font-size: 40rpx;

      &.vip-active {
        background: linear-gradient(135deg, #FFD700, #FFA500);
      }

      &.vip-inactive {
        background-color: #f5f5f5;
      }
    }

    .status-info {
      flex: 1;

      .status-title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }

      .status-desc {
        font-size: 24rpx;
        color: var(--tn-text-color-secondary);
      }
    }
  }

  .usage-progress {
    margin-bottom: 30rpx;

    .progress-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15rpx;
      font-size: 26rpx;
      color: var(--tn-text-color-secondary);
    }

    .progress-bar {
      height: 12rpx;
      background-color: #f0f0f0;
      border-radius: 6rpx;
      overflow: hidden;

      .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #1890ff, #52c41a);
        border-radius: 6rpx;
        transition: width 0.3s ease;
      }
    }
  }
}

// 套餐列表
.vip-packages {
  margin-bottom: 30rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: var(--tn-text-color-primary);
  }

  .package-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }

  .package-item {
    border-radius: 20rpx;
    padding: 30rpx;
    position: relative;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

    &.popular {
      border: 2rpx solid #1890ff;
    }

    .popular-badge {
      position: absolute;
      top: -10rpx;
      right: 20rpx;
      background: linear-gradient(135deg, #1890ff, #52c41a);
      color: white;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 20rpx;
    }

    .package-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15rpx;

      .package-name {
        font-size: 28rpx;
        font-weight: bold;
      }

      .package-price {
        display: flex;
        align-items: center;
        gap: 10rpx;

        .current-price {
          font-size: 32rpx;
          font-weight: bold;
          color: #f5222d;
        }

        .original-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }

        .discount-badge {
          background-color: #f5222d;
          color: white;
          padding: 4rpx 8rpx;
          border-radius: 8rpx;
          font-size: 20rpx;
        }
      }
    }

    .package-duration {
      font-size: 24rpx;
      color: var(--tn-text-color-secondary);
      margin-bottom: 20rpx;
    }

    .package-features {
      margin-bottom: 20rpx;

      .feature-item {
        display: flex;
        align-items: center;
        gap: 10rpx;
        margin-bottom: 10rpx;
        font-size: 24rpx;
        color: var(--tn-text-color-secondary);
      }
    }
  }
}

// 广告奖励
.ad-rewards {
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: var(--tn-text-color-primary);
  }

  .reward-list {
    display: flex;
    flex-direction: column;
    gap: 15rpx;
  }

  .reward-item {
    border-radius: 20rpx;
    padding: 25rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

    .reward-icon {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
      font-size: 28rpx;
    }

    .reward-info {
      flex: 1;

      .reward-name {
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 5rpx;
      }

      .reward-desc {
        font-size: 22rpx;
        color: var(--tn-text-color-secondary);
      }
    }

    .reward-value {
      font-size: 26rpx;
      font-weight: bold;
      color: #52c41a;
      margin-right: 15rpx;
    }
  }
}
</style> 